<?php
declare (strict_types = 1);

namespace app\admin\controller;
use app\admin\logic\lawyer\RemindLogic;
use app\common\controller\AdminBase;
use app\common\helper\MenuHelper;
use app\common\model\AuthRule;
use app\common\model\OrderOrder;
use app\common\model\OrderOther;
use app\common\model\OrderProject;
use app\common\model\PrintJie;
use app\common\model\PrintShare;
use app\common\model\PrintYan;
use app\common\model\Project;
use app\common\model\ProjectItem;
use app\common\model\ProjectItemLawyer;
use think\db\Query;
use think\exception\ValidateException;
use app\common\model\ProjectItem as itemModel;
use think\facade\View;

class Index extends AdminBase
{
    public function index()
    {
        $menus = AuthRule::where(['is_menu'=>1])->order('sort desc')->select()->toArray();
        $menus = MenuHelper::MakeMenu($menus);
        View::assign("menu",json_encode($menus));
        $menuslist = ['menus'=>$menus];
        View::assign('menus', json_encode($menuslist));
        if ($this->request->isAjax()) {
            $this->successData($menuslist);
        }
        return View::fetch();
    }

    public function main()
    {
        $ver = $this->app->version();
        $php[] = php_uname('s').php_uname('r') ;
        $php[] = PHP_VERSION;
        $php[] = $_SERVER["HTTP_HOST"];
        $php[] = php_sapi_name() ;
        $php[] = get_cfg_var ("upload_max_filesize")?get_cfg_var ("upload_max_filesize"):"不允许";
        $php[] = $_SERVER['SERVER_PROTOCOL'];
        $view = [
            "ver" => $ver,
            "php" => $php
        ];
        View::assign($view);
        return View::fetch();
    }

    public function password()
    {
        if ($this->request->isPost()) {
            $rule = [
                "password|密码" => "require|confirm",
                "old_password|旧密码" => "require"
            ];
            $data = input();
            try {
                $this->validate($data,$rule);
            } catch (ValidateException $exception) {
                $this->error($exception->getMessage());
            }

            $id = session('admin.id');
            $user = \app\common\model\Admin::find($id);
            if ($user) {
                if (password_verify($data['old_password'], $user->pass_word)) {
                    $user->pass_word = password_hash($data['password'], PASSWORD_DEFAULT);
                    $user->save();
                    return $this->success();
                } else {
                    return $this->error('旧密码不对');
                }
            }
            return $this->error();
        }
        return View::fetch();
    }

    // 刷新个人权限
    public function refresh()
    {
        $user = \app\common\model\Admin::find(session('admin.id'));
        if ($user) {
            unset($user['pass_word']);
            $user['rules'] = $user->authGroup->rules; // 设置用户权限
            session('admin', $user);
            return $this->success();
        }
        return $this->error();
    }

    //图表统计
    public function statistics()
    {
        $diggings = [
            "day" => \app\common\model\Diggings::whereDay('create_time')->count(),
            "all" => \app\common\model\Diggings::count(),
            "status" => \app\common\model\Diggings::where('status', 1)->count(),
        ];
    
        $factory = [
            "day" => \app\common\model\Factory::whereDay('create_time')->count(),
            "all" => \app\common\model\Factory::count(),
            "status" => \app\common\model\Factory::where('status', 1)->count(),
        ];
        
        $parts = [
            "day" => \app\common\model\Parts::whereDay('create_time')->count(),
            "all" => \app\common\model\Parts::count(),
            "status" => \app\common\model\Parts::where('status', 1)->count(),
        ];
    
        $yan = [
            "day" => \app\common\model\PrintYan::whereDay('create_time')->count(),
            "all" => \app\common\model\PrintYan::count(),
        ];
    
        $share = [
            "day" => \app\common\model\PrintShare::whereDay('create_time')->count(),
            "all" => \app\common\model\PrintShare::count(),
        ];
        
        $this->success(
            [
                "diggings" => $diggings,
                "factory" => $factory,
                "yan" => $yan,
                "share" => $share,
                "parts" => $parts,
            ]
        );
    }
    // 各中心订单统计
    public function getOrderCount()
    {
        if (session("admin.auth_group_id") != 1) {
            $diggings = \app\common\model\Diggings::where('id', session("admin.diggings_id"))->select();
        } else {
            $diggings = \app\common\model\Diggings::select();
        }
        
        $list = [];
        $day = date('d');
        $month = date('m');
        $last_month = $month - 1;

        if ($day <21) {
            $start_time = strtotime(date("Y-{$last_month}-21"));
            $end_time = strtotime(date("Y-m-20 23:59:59"));
        } else {
            $start_time = strtotime(date("Y-m-21"));
            $end_time = strtotime("+1 month", $start_time - 1);
        }
        
        $year_start = strtotime(date("Y-01-01"));
        $year_end = time();
        

        
        foreach ($diggings as $item) {
            $map1 = [
                ['create_time','between',[$year_start,$year_end]],
                ['diggings_id','=',$item["id"]],
                ['status','=',1],
        
                ['liu_time','NULL',null]
            ];
            $map2 = [
                ['diggings_id','=',$item["id"]],
                ['liu_time','between',[$year_start,$year_end]],
                ['status','=',1],
            ];
            $year_money = [
                OrderOrder::order('id desc')
                    ->whereOr([$map1,$map2])
                    ->sum('total_money'),
                OrderProject::whereOr([$map1,$map2])
                    ->sum('total_money'),
                OrderOther::whereOr([$map1,$map2])
                    ->sum('total_money'),
                PrintShare::where("diggings_id",$item["id"])
                    ->where("create_time",">",$start_time)
                    ->sum('price'),
            ];
            
            
            $map1 = [
                ['create_time','between',[$start_time,$end_time]],
                ['diggings_id','=',$item["id"]],
                ['status','=',1],
    
                ['liu_time','NULL',null]
            ];
            $map2 = [
                ['diggings_id','=',$item["id"]],
                ['liu_time','between',[$start_time,$end_time]],
                ['status','=',1],
            ];
            
            $sum_money = [
                OrderOrder::order('id desc')
                    ->whereOr([$map1,$map2])
                    ->sum('total_money'),
                OrderProject::whereOr([$map1,$map2])
                    ->sum('total_money'),
                OrderOther::whereOr([$map1,$map2])
                    ->sum('total_money'),
                PrintShare::where("diggings_id",$item["id"])
                    ->where("create_time",">",$start_time)
                    ->sum('price'),
            ];
            
            $list[] = [
                "title" => $item["title"],
                
                "weixiu" => OrderOrder::where("diggings_id", $item["id"])
                    ->where("create_time",">",$start_time)
                    ->where('status', 1)
                    ->count(),
                "weixiu_money" => OrderOrder::order('id desc')
                    ->whereOr([$map1,$map2])
                    ->sum('total_money'),
          
                "project" => OrderProject::where("diggings_id", $item["id"])
                    ->where("create_time",">",$start_time)
                    ->where('status', 1)
                    ->count(),
                "project_money" => OrderProject::whereOr([$map1,$map2])
                    ->sum('total_money'),
                
                "other" => OrderOther::where("diggings_id", $item["id"])
                    ->where("create_time",">",$start_time)
                    ->where('status', 1)
                    ->count(),
                "other_money" => OrderOther::whereOr([$map1,$map2])
                    ->sum('total_money'),

                "share" => PrintShare::where("diggings_id",$item["id"])
                    ->where("create_time",">",$start_time)
                    ->count(),
                "share_money" => PrintShare::where("diggings_id",$item["id"])
                    ->where("create_time",">",$start_time)
                    ->sum('price'),
                
                "all_money" => round(array_sum($sum_money),2),
                "year_money" => round(array_sum($year_money),2),
            ];
        }
        $this->success($list);
    }
    
    // 折线图
    public function zhexian()
    {
        $day = date('d');
        $month = date('m');
        $last_monty = $month - 1;
        if ($day <21) {
            $start_time = strtotime(date("Y-{$last_monty}-21"));
        } else {
            $start_time = strtotime(date("Y-m-21"));
        }
        $list = [];
        $where = [];
        if (session("admin.auth_group_id") != 1) {
            $where[] = ["admin","=", session("admin.diggings_id")];
        }
        while ($start_time <= time()) {
            $order_money = [
                OrderOrder::order('id desc')
                    ->where($where)
                    ->whereDay('create_time', date("Y-m-d",$start_time))
                    ->sum('total_money'),
                OrderOther::order('id desc')
                    ->where($where)
                    ->whereDay('create_time', date("Y-m-d",$start_time))
                    ->sum('total_money'),
                OrderProject::order('id desc')
                    ->where($where)
                    ->whereDay('create_time', date("Y-m-d",$start_time))
                    ->sum('total_money'),
            ];
            $map1 = [
                ['create_time','between',[$start_time,$start_time + 86399]],
                ['status','=',1],
                ['liu_time','NULL',null]
            ];
            $map2 = [
                ['liu_time','between',[$start_time,$start_time + 86399]],
                ['status','=',1],
            ];
            $jie_money = [
                OrderOrder::order('id desc')
                    ->where($where)
                    ->whereOr([$map1,$map2])
                    ->sum('total_money'),
                OrderOther::order('id desc')
                    ->where($where)
                    ->whereOr([$map1,$map2])
                    ->sum('total_money'),
                OrderProject::order('id desc')
                    ->where($where)
                    ->whereOr([$map1,$map2])
                    ->sum('total_money'),
            ];
            $liu_money = [
                OrderOrder::order('id desc')
                    ->where($where)
                    ->whereDay('create_time', date("Y-m-d",$start_time))
                    ->whereNotNull('liu_time')
                    ->where('status','<>',1)
                    ->sum('total_money'),
                OrderOther::order('id desc')
                    ->where($where)
                    ->whereDay('create_time', date("Y-m-d",$start_time))
                    ->whereNotNull('liu_time')
                    ->where('status','<>',1)
                    ->sum('total_money'),
                OrderProject::order('id desc')
                    ->where($where)
                    ->whereDay('create_time', date("Y-m-d",$start_time))
                    ->whereNotNull('liu_time')
                    ->where('status','<>',1)
                    ->sum('total_money'),
            ];
            
            
            
            $list[] = [
                "time" => date("m-d",$start_time),
                "count" => round(array_sum($order_money),2),
                "jie" => round(array_sum($jie_money),2),
                "liu" => round(array_sum($liu_money),2),
            ];
            $start_time += 86400;
        }
        $day = array_column($list,'time');
        $series = [
            [
                "name"=> '订单金额',
                "type"=>  'line',
                "data"=>  array_column($list,'count')
            ],
            [
                "name"=> '结算金额',
                "type"=>  'line',
                "data"=>  array_column($list,'jie')
            ],
            [
                "name"=> '流转金额',
                "type"=>  'line',
                "data"=>  array_column($list,'liu')
            ]
        ];
        
        $this->success([
            "day" => $day,
            "series" => $series,
        ]);
    }
    
    // 饼状图
    public function getPie() {
        $year = date('Y');
        $day = date('d');
        $month = date('m');
        $last_month  = $month - 1;
        if ($day <21) {
            $temp_start = strtotime(date("Y-{$last_month}-21"));
            $end_time = strtotime(date("Y-m-20 23:59:59"));
        } else {
            $temp_start = strtotime(date("Y-m-21"));
            $end_time = strtotime("+1 month", $temp_start - 1);
        }
        $where = [];
        if (session("admin.auth_group_id") != 1) {
            $where[] = ["admin","=", session("admin.diggings_id")];
        }
        // pie
        $other_count = OrderOther::where('create_time',">",$temp_start)->where($where)->count();
        $other_money = OrderOther::where('create_time',">",$temp_start)->where($where)->sum('total_money');
    
        $wei_count = OrderOrder::where('create_time',">",$temp_start)->where($where)->count();
        $wei_money = OrderOrder::where('create_time',">",$temp_start)->where($where)->sum('total_money');
    
        $project_count = OrderProject::where('create_time',">",$temp_start)->where($where)->count();
        $project_money = OrderProject::where('create_time',">",$temp_start)->where($where)->sum('total_money');
        
        
        $jie_money = OrderOrder::where('create_time',">",$temp_start)->where($where)
            ->where('status',1)
            ->sum('total_money');
    
        $liu_money = OrderOrder::where('liu_time',">",$temp_start)->where($where)->sum('total_money');
    
        $data1 = [
            [
                "name" => "本月其它订单数据",
                "value" => $other_count
            ],
            [
                "name" => "本月工程订单数据",
                "value" => $project_count
            ],
            [
                "name" => "本月维修订单数据",
                "value" => $wei_count
            ]
        ];
    
        $data2 = [
            [
                "name" => "本月其它订单金额",
                "value" => $other_money
            ],
            [
                "name" => "本月工程订单金额",
                "value" => $project_money
            ],
            [
                "name" => "本月维修订单金额",
                "value" => $wei_money
            ]
        ];
    
    
        $map1 = [
            ['create_time','between',[$temp_start,time()]],
            ['status','=',1],
            ['liu_time','NULL',null]
        ];
        $map2 = [
            ['liu_time','between',[$temp_start,time()]],
            ['status','=',1],
        ];
        
        $jie_money = [
            OrderOrder::order('id desc')
                ->where($where)
                ->whereOr([$map1,$map2])
                ->sum('total_money'),
            OrderOther::order('id desc')
                ->where($where)
                ->whereOr([$map1,$map2])
                ->sum('total_money'),
            OrderProject::order('id desc')
                ->where($where)
                ->whereOr([$map1,$map2])
                ->sum('total_money'),
        ];
        $liu_money = [
            OrderOrder::order('id desc')
                ->where($where)
                ->whereBetweenTime('create_time', date('Y-m-d',$temp_start),date('Y-m-20',time()))
                ->whereNotNull('liu_time')
                ->where('status','<>',1)
                ->sum('total_money'),
            OrderOther::order('id desc')
                ->where($where)
                ->whereBetweenTime('create_time', date('Y-m-d',$temp_start),date('Y-m-20',time()))
                ->whereNotNull('liu_time')
                ->where('status','<>',1)
                ->sum('total_money'),
            OrderProject::order('id desc')
                ->where($where)
                ->whereBetweenTime('create_time', date('Y-m-d',$temp_start),date('Y-m-20',time()))
                ->whereNotNull('liu_time')
                ->where('status','<>',1)
                ->sum('total_money'),
        ];
        $data3 = [
            [
                "name" => "本月结算订单金额",
                "value" => round(array_sum($jie_money),2)
            ],
            [
                "name" => "本月流转订单金额",
                "value" => round(array_sum($liu_money),2)
            ]
        ];
    
        $this->success([
            "data1" => $data1,
            "data2" => $data2,
            "data3" => $data3
        ]);
    }
    
    // 折线2
    public function yearData()
    {
        $list = [
            ["1-21","2-20 23:59:59"],
            ["2-21","3-20 23:59:59"],
            ["3-21","4-20 23:59:59"],
            ["4-21","5-20 23:59:59"],
            ["5-21","6-20 23:59:59"],
            ["6-21","7-20 23:59:59"],
            ["7-21","8-20 23:59:59"],
            ["8-21","9-20 23:59:59"],
            ["9-21","10-20 23:59:59"],
            ["10-21","11-20 23:59:59"],
        ];
        $where = [];
        if (session("admin.auth_group_id") != 1) {
            $where[] = ["admin","=", session("admin.diggings_id")];
        }
        $result = [];
        foreach ($list as $item) {
            $start_time = strtotime(date("Y-" . $item[0]));
            $end_time = strtotime(date('Y-') . $item[1]);
            $order_money = [
                OrderOrder::order('id desc')
                    ->where($where)
                    ->whereBetweenTime('create_time', date("Y-m-d",$start_time),date("Y-m-d H:i:s",$end_time))
                    ->sum('total_money'),
                OrderOther::order('id desc')
                    ->where($where)
                    ->whereBetweenTime('create_time', date("Y-m-d",$start_time),date("Y-m-d H:i:s",$end_time))
                    ->sum('total_money'),
                OrderProject::order('id desc')
                    ->where($where)
                    ->whereBetweenTime('create_time', date("Y-m-d",$start_time),date("Y-m-d H:i:s",$end_time))
                    ->sum('total_money'),
            ];
            $map1 = [
                ['create_time','between',[$start_time,$end_time]],
                ['status','=',1],
                ['liu_time','NULL',null]
            ];
            $map2 = [
                ['liu_time','between',[$start_time,$end_time]],
                ['status','=',1],
            ];
            $jie_money = [
                OrderOrder::order('id desc')
                    ->where($where)
                    ->whereOr([$map1,$map2])
                    ->sum('total_money'),
                OrderOther::order('id desc')
                    ->where($where)
                    ->whereOr([$map1,$map2])
                    ->sum('total_money'),
                OrderProject::order('id desc')
                    ->where($where)
                    ->whereOr([$map1,$map2])
                    ->sum('total_money'),
            ];
            $liu_money = [
                OrderOrder::order('id desc')
                    ->where($where)
                    ->whereBetweenTime('create_time', date("Y-m-d",$start_time),date("Y-m-d H:i:s",$end_time))
                    ->whereNotNull('liu_time')
                    ->where('status','<>',1)
                    ->sum('total_money'),
                OrderOther::order('id desc')
                    ->where($where)
                    ->whereBetweenTime('create_time', date("Y-m-d",$start_time),date("Y-m-d H:i:s",$end_time))
                    ->whereNotNull('liu_time')
                    ->where('status','<>',1)
                    ->sum('total_money'),
                OrderProject::order('id desc')
                    ->where($where)
                    ->whereBetweenTime('create_time', date("Y-m-d",$start_time),date("Y-m-d H:i:s",$end_time))
                    ->whereNotNull('liu_time')
                    ->where('status','<>',1)
                    ->sum('total_money'),
            ];
            $result[] = [
                "time" => date("m月d日",$start_time) . "--" . date("m月d日",$end_time),
                "count" => round(array_sum($order_money),2),
                "jie" => round(array_sum($jie_money),2),
                "liu" => round(array_sum($liu_money),2),
            ];
        }
        $day = array_column($result,'time');
        $series = [
            [
                "name"=> '订单金额',
                "type"=>  'line',
                "data"=>  array_column($result,'count')
            ],
            [
                "name"=> '结算金额',
                "type"=>  'line',
                "data"=>  array_column($result,'jie')
            ],
            [
                "name"=> '流转金额',
                "type"=>  'line',
                "data"=>  array_column($result,'liu')
            ]
        ];
    
        $this->success([
            "day" => $day,
            "series" => $series,
        ]);
    }
}
